﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace FilesNameCopier
{
  static class Program
  {
    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    [STAThread]
    static void Main(string[] args)
    {
      if (args.Length > 0)
      {
        try
        {
          string modeName = FilesNameCopier.Properties.Settings.Default.DefaultCapture.ToLower();
          FileNameMode mode;

          if (modeName.IndexOf("long") != -1)
            mode = FileNameMode.LongName;
          else if (modeName.IndexOf("short") != -1)
            mode = FileNameMode.ShortName;
          else
            mode = FileNameMode.FullPath;

          ProcessFiles(args, mode, null);
          return;
        }
        catch (Exception) { }

        RunApp();
      }
      else
      {
        RunApp();
      }
    }

    private static void RunApp()
    {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new CopierForm());
    }

    private static string NameFormatter(string fileName, bool dateTime, bool size)
    {
      string dateTimeString;
      string sizeString;

      try
      {
        if (dateTime || size)
        {
          if (File.Exists(fileName))
          {
            FileInfo fi = new FileInfo(fileName);
            dateTimeString = dateTime ? string.Format("\t{0:G}", fi.CreationTime) : "";
            sizeString = size ? string.Format("\t{0:N0}", fi.Length) : "";
          }
          else if (Directory.Exists(fileName))
          {
            DirectoryInfo di = new DirectoryInfo(fileName);
            dateTimeString = dateTime ? string.Format("\t{0:G}", di.CreationTime) : "";
            sizeString = "";
          }
          else
          {
            dateTimeString = "";
            sizeString = "";
          }
          return dateTimeString + sizeString;
        }
      }
      catch { }

      return "";
    }

    internal static void ProcessFiles(string[] fileNames, FileNameMode mode, Form owner)
    {
      bool dateTime = FilesNameCopier.Properties.Settings.Default.CaptureFileDateTime;
      bool size = FilesNameCopier.Properties.Settings.Default.CaptureFileSize;

      IEnumerable<string> names;

      switch (mode)
      {
        case FileNameMode.FullPath:
          names = fileNames.Select(X => X + NameFormatter(X, dateTime, size));
          break;
        case FileNameMode.LongName:
          names = fileNames.Select(X => Path.GetFileName(X) + NameFormatter(X, dateTime, size));
          break;
        case FileNameMode.ShortName:
        default:
          names = fileNames.Select(X => Path.GetFileNameWithoutExtension(X) + NameFormatter(X, dateTime, size));
          break;
      }

      string data;
      data = string.Join("\r\n", names);
      Clipboard.SetText(data);
      OpenNotepad();
      SaveFile(names, owner);
    }

    private static void SaveFile(IEnumerable<string> names, Form owner)
    {
      if (FilesNameCopier.Properties.Settings.Default.SaveDialog)
      {
        using (SaveFileDialog fsd = new SaveFileDialog())
        {
          fsd.DefaultExt = "txt";
          fsd.Filter = "Text Files|*.txt|Xml Files|*.xml";
          fsd.Title = "Save File list";

          if (fsd.ShowDialog(owner) == DialogResult.OK)
            if (Path.GetExtension(fsd.FileName).ToLower() == ".xml")
            {
              StringBuilder xml = new StringBuilder();
              xml.AppendLine("<Files>");
              foreach (string name in names)
                xml.AppendFormat(" <File>{0}</File>\r\n", name);
              xml.AppendLine("</Files>");
              File.WriteAllText(fsd.FileName, xml.ToString());
            }
            else
              File.WriteAllLines(fsd.FileName, names.ToArray());
        }
      }
    }

    private static void OpenNotepad()
    {
      if (FilesNameCopier.Properties.Settings.Default.OpenNotepad)
      {
        Process notepad = Process.Start("Notepad.exe");
        notepad.WaitForInputIdle();

        IntPtr p = notepad.MainWindowHandle;
        ShowWindow(p, 1);
        SendKeys.SendWait("^V");
      }
    }

    internal static void ShowAbout(Form owner)
    {
      string cr = "";
      Assembly asm = Assembly.GetExecutingAssembly();
      object[] obj = asm.GetCustomAttributes(false);
      foreach (object o in obj)
      {
        if (o.GetType() == typeof(System.Reflection.AssemblyCopyrightAttribute))
        {
          AssemblyCopyrightAttribute aca = (AssemblyCopyrightAttribute)o;
          cr = aca.Copyright;
        }
      }

      StringBuilder message = new StringBuilder(256);
      message.Append(string.Format("{0}.\r\n\r\n", Application.ProductName));
      message.Append(string.Format("Version: {0}.\r\n\r\n", Application.ProductVersion.ToString()));
      message.Append(string.Format("{0}.\r\n", cr));

      MessageBox.Show(owner, message.ToString(), string.Format("About {0}", Application.ProductName), MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
  }
}